package com.gopay.common;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import org.apache.log4j.Logger;

import com.caucho.hessian.client.HessianProxyFactory;
import com.gopay.common.hessian.SendHessianKey;

/**
 * Custom Hessian代理工厂
 * 
 * @CustomHessianProxyFactory.java
 * @author MA HUAN
 * @author KZ-TU
 * @2013-1-17 上午11:43:35 www.gopay.com.cn Inc.All rights reserved.
 */
public class CustomHessianProxyFactory extends HessianProxyFactory {

    private static final Logger logger = Logger.getLogger(CustomHessianProxyFactory.class);

    /**
     * connectTimeOut an int that specifies the timeout value to be used in
     * milliseconds
     */
    private int connectTimeOut = 0;
    /**
     * readTimeOut an int that specifies the timeout value to be used in
     * milliseconds
     */
    private int readTimeOut = 0;
    /**
     * Hostname verifier used when making an SSL request to the remote service.
     */
    private HostnameVerifier hostnameVerifier;

    public CustomHessianProxyFactory() {
        super();
        // 在调用openConnection之前就会判断这些属性值，所以在构造方法里面进行初始化设置。
        setChunkedPost(false);
        setOverloadEnabled(true);
        this.hostnameVerifier = new CustomHostnameVerifier();
    }

    @Override
    public URLConnection openConnection(URL url) throws IOException {
        URLConnection conn = super.openConnection(url);
        
        // modified by kz-tu 20131203 支持Hessian的https远程调用
        if (conn instanceof HttpsURLConnection) {
//            logger.info("[openConnection]URLConnection is HttpsURLConnection, Url:" + url);
            ((HttpsURLConnection)conn).setHostnameVerifier(hostnameVerifier);
        }else{
//            logger.info("[openConnection]URLConnection is HttpURLConnection, Url:" + url);
        }

        conn.setDoOutput(true);
        conn.setRequestProperty("Token-Key", SendHessianKey.getInstance());

        if (this.connectTimeOut > 0) {
            conn.setConnectTimeout(this.connectTimeOut);
            if (logger.isDebugEnabled()) {
                logger.debug("Set Hessian Connection Timeout :" + this.connectTimeOut);
            }
        }

        if (this.readTimeOut > 0) {
            conn.setReadTimeout(this.readTimeOut);
            if (logger.isDebugEnabled()) {
                logger.debug("Set Hessian Read Timeout :" + this.readTimeOut);
            }
        }

        return conn;
    }

    public int getConnectTimeOut() {
        return connectTimeOut;
    }

    public void setConnectTimeOut(int connectTimeOut) {
        this.connectTimeOut = connectTimeOut;
    }

    public int getReadTimeOut() {
        return readTimeOut;
    }

    public void setReadTimeOut(int readTimeOut) {
        this.readTimeOut = readTimeOut;
    }
}
